package com.soft.admin.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.soft.admin.common.ElementConst;
import com.soft.admin.dto.ComboDTO;
import com.soft.admin.dto.DeviceDTO;
import com.soft.admin.service.DeviceService;
import com.soft.dao.DeviceDao;
import com.soft.model.Channel;
import com.soft.model.Device;
import com.soft.model.User;
import com.soft.support.PageParam;
import com.soft.support.Pager;
import com.soft.util.DateUtil;
import com.soft.util.FileUtil;
import com.soft.util.JsonUtil;
import com.soft.util.RequestUtil;

@SuppressWarnings("unchecked")
@Component
public class DeviceServiceImpl implements DeviceService {
	private DeviceDao deviceDao;

	@Autowired
	public void setDeviceDao(DeviceDao deviceDao) {
		this.deviceDao = deviceDao;
	}
	
	@Transactional(readOnly = true)
	public String get(DeviceDTO params, PageParam page) {
		List<Criterion> values = new ArrayList<Criterion>();
		values.add(Restrictions.like("title", params.getTitle(), MatchMode.ANYWHERE));
		if (params.getChannel() != -1) {
			values.add(Restrictions.eq("channel.id", params.getChannel()));
		}
		if (params.getState() != -1) {
			values.add(Restrictions.eq("state", params.getState()));
		}
		Pager deviceLst = this.deviceDao.findForPager(Device.class, 
				new Order[] { Order.desc("level"), Order.desc("releaseDate"), Order.desc("id") }, 
				page.getStart(), page.getLimit(), values);
		Pager pageModel = new Pager();
		pageModel.setTotal(deviceLst.getTotal());
		List<DeviceDTO> dtos = new ArrayList<DeviceDTO>();
		for (Device device : (List<Device>)deviceLst.getDatas()) {
			DeviceDTO dto = new DeviceDTO();
			BeanUtils.copyProperties(device, dto, new String[]{"channel", "user", "releaseDate", "updateDate"});
			dto.setChannel(device.getChannel().getId());
			dto.setUser(device.getUser().getId());
			dto.setReleaseDate(DateUtil.format(device.getReleaseDate()));
			dto.setUpdateDate(DateUtil.format(device.getUpdateDate()));
			dtos.add(dto);
		}
		pageModel.setDatas(dtos);
		return JsonUtil.toStringFromObject(pageModel);
	}

	@Transactional
	public String addOrEdit(HttpServletRequest request, DeviceDTO params) {
		Device device = null;
		if (params.getId() == null) {
			device = new Device();
			User user = (User)this.deviceDao.findUniqueByProperty(User.class, "username", RequestUtil.getUsername());
			device.setUser(user);
		} else {
			device = (Device)this.deviceDao.get(Device.class, params.getId());
		}
		MultipartHttpServletRequest mulrequest = (MultipartHttpServletRequest)request;
		CommonsMultipartFile file = (CommonsMultipartFile)mulrequest.getFile("filepic");
		if (file.getSize() > 0) {
			DiskFileItem fileItem = (DiskFileItem) file.getFileItem();
			String fileStr = fileItem.getName().substring(fileItem.getName().lastIndexOf(".")).toLowerCase();
			if (!".jpg".equals(fileStr) 
					&& !".png".equals(fileStr) 
					&& !".bmp".equals(fileStr) 
					&& !".gif".equals(fileStr)) {
				return JsonUtil.toRes("保存失败！", "图片格式错误");
			}
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss")+ fileStr;
			String rootPath = request.getSession().getServletContext().getRealPath(ElementConst.IMGSPATH);
			String path = rootPath + File.separator + FileUtil.getPath(fileName) + File.separator;
			File targetDir = new File(path);
			if (!targetDir.exists()) targetDir.mkdirs();
			try {
				FileCopyUtils.copy(file.getBytes(), new File(path + fileName));
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (device.getTitleImg() != null && !"".equals(device.getTitleImg())) {
				FileUtil.delete(rootPath + File.separator + device.getTitleImg());
			}
			device.setTitleImg(FileUtil.getPath(fileName) + "/" + fileName);
		}
		device.setLevel(params.getLevel());
		device.setReleaseDate(DateUtil.format(params.getReleaseDate()));
		device.setUpdateDate(new Date());
		device.setState(params.getState());
		device.setTitle(params.getTitle());
		device.setTxt(params.getTxt());
		Channel channel = (Channel)this.deviceDao.get(Channel.class, params.getChannel());
		device.setChannel(channel);
		this.deviceDao.addOrEdit(device);
		return JsonUtil.toRes("保存成功！");
	}

	@Transactional
	public String remove(HttpServletRequest request, Integer id) {
		Device device = (Device)this.deviceDao.get(Device.class, id);
		if (device.getTitleImg() != null && !"".equals(device.getTitleImg())) {
			String rootPath = request.getSession().getServletContext().getRealPath(ElementConst.IMGSPATH);
			FileUtil.delete(rootPath + File.separator + device.getTitleImg());
		}
		this.deviceDao.remove(device);
		return JsonUtil.toRes("删除成功！");
	}

	@Transactional(readOnly = true)
	public String getChannel() {
		Channel chan = (Channel)this.deviceDao.findUniqueByProperty(Channel.class, "namespace", ElementConst.YQSBCONST);
		List<Channel> channels = this.deviceDao.findAll(Channel.class, null, Restrictions.eq("parent.id", chan.getId()));
		List<ComboDTO> dtos = new ArrayList<ComboDTO>();
		for (Channel channel : channels) {
			ComboDTO dto = new ComboDTO();
			dto.setId(channel.getId());
			dto.setStr(channel.getName());
			dtos.add(dto);
		}
		return JsonUtil.toString(dtos);
	}

	@Transactional(readOnly = true)
	public String getUser() {
		List<User> users = this.deviceDao.findAll(User.class, null);
		List<ComboDTO> dtos = new ArrayList<ComboDTO>();
		for (User user : users) {
			ComboDTO dto = new ComboDTO();
			dto.setId(user.getId());
			dto.setStr(user.getTruename());
			dtos.add(dto);
		}
		return JsonUtil.toString(dtos);
	}
}
